package com.alinesno.cloud.common.web.base.advice.plugins;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.alinesno.cloud.base.boot.entity.ManagerCodeEntity;
import com.alinesno.cloud.base.boot.service.IManagerCodeService;
import com.alinesno.cloud.common.web.base.advice.TranslateCode;
import com.alinesno.cloud.common.web.base.advice.TranslatePlugin;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

/**
 * 代码转换插件
 * @author WeiXiaoJin
 * @since 2019年4月7日 下午2:23:50
 */
@Component
public class DirectoryPlugin implements TranslatePlugin {

//	@Autowired
	@Autowired
	private IManagerCodeService managerCodeService ; 
	
	private static Map<String , ManagerCodeEntity> listCode = null ; 
	
	@Override
	public void translate(JSONObject node, TranslateCode convertCode) {

		// 解析注解
		String fieldJson = convertCode.value() ; 
		if(StringUtils.isBlank(fieldJson)) {
			return ; 
		}
		
		JsonArray fieldArr = (JsonArray)parser.parse(fieldJson);
					
		log.trace("====> 开始代码转换_start:{}" , node); 
		for(JsonElement convertEle : fieldArr) {
			
			JsonObject convertObj = convertEle.getAsJsonObject() ;
			for (String convertFieldName :convertObj.keySet()) {
				if(StringUtils.isBlank(convertFieldName) || node == null) {
					continue ; 
				}
				String convertFieldValue = node.get(convertFieldName)+"" ; // node.getAsJsonObject().get(convertFieldName).getAsString() ; 
				String convertFieldCodeType = convertObj.get(convertFieldName).getAsString() ; 
				
				log.trace("fieldName = {} , codeType = {} , fieldValue = {}" , convertFieldName , convertFieldCodeType , convertFieldValue);
				
				node.put(convertFieldName+"Label", queryName(convertFieldCodeType , convertFieldValue)); 
			}
		}	
		log.trace("====> 结束代码转换_end :{}" , node); 
	}

	/**
	 * 初始化代码字典
	 * @param IManagerCodeService2
	 * @return 
	 */
	private String queryName(String codeType , String codeValue) {
		// log.debug("listCode:{}" , listCode);
		
		if(listCode == null) { // 第一次初始化
			
			listCode = new HashMap<String , ManagerCodeEntity>() ; 
			
			List<ManagerCodeEntity> list = managerCodeService.findAll() ; 
			for(ManagerCodeEntity l : list) {
				listCode.put(l.getCodeTypeValue()+"_"+l.getCodeValue() , l) ;
			}
			
		}
		
		// TODO 待优化
		ManagerCodeEntity m = listCode.get(codeType+"_"+codeValue) ; 
		return m == null?null:m.getCodeName(); 
	}

}
